package org.vt.ece4564.pcw.textinclass;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class RegisterRequest extends AsyncTask<Void, Void, Void> {
	
	private String username_;
	private String name_;
	private String password_;
	private String passwordReenter_;
	private RegisterUserActivity registerUserActivity_;
	
	private final String URL = "http://pcw-textinclass.appspot.com/registerUser";
	
	private String responseString_ = "";
	private boolean success_ = false;
	
	public RegisterRequest(String username, String name, String password,
			String passwordReenter, RegisterUserActivity registerUserActivity) {
		
		super();
		username_ = username;
		name_ = name;
		password_ = password;
		passwordReenter_ = passwordReenter;
		registerUserActivity_ = registerUserActivity;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(URL);
			CookieStore cookies = new BasicCookieStore();
			HttpContext localContext = new BasicHttpContext();
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
			
			String phoneID = PhoneIDGenerator.getPhoneID(registerUserActivity_);
			
			List<NameValuePair> data = new ArrayList<NameValuePair>();
			
			data.add(new BasicNameValuePair("username", username_));
			data.add(new BasicNameValuePair("name", name_));
			data.add(new BasicNameValuePair("phoneID", phoneID));
			data.add(new BasicNameValuePair("password", password_));
			data.add(new BasicNameValuePair("password_reenter", passwordReenter_));
			
			HttpEntity entity = new UrlEncodedFormEntity(data);
			
			post.setEntity(entity);
			
			HttpResponse response = client.execute(post, localContext);
			
			if (response.getStatusLine().getStatusCode() != 200) {
				Log.d("RegisterRequestError", response.getStatusLine().toString());
				return null;
			}
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			
			String line;
			
			while ((line = reader.readLine()) != null) {
				responseString_ += line;
			}
			
			if (responseString_.equals("Success")) {
				success_ = true;
				Log.d("success", "success");
			}
			
		} catch (Exception e) {
			Log.d("RegisterRequestException", e.toString());
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		if (success_) {
			Intent intent = new Intent(registerUserActivity_, LoginActivity.class);
			
			SharedPreferences settings = registerUserActivity_.getSharedPreferences("TextInClassPrefs", Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();
			
			editor.putBoolean("registered", true);
			
			if (!editor.commit()) {
				Toast toast = Toast.makeText(registerUserActivity_.getApplicationContext(),
					"Unable to commit", Toast.LENGTH_SHORT);
				toast.show();
			}
			
			registerUserActivity_.startActivity(intent);
		}
		else {
			registerUserActivity_.resetScreen();
			
			Toast toast = Toast.makeText(registerUserActivity_.getApplicationContext(), 
					responseString_, Toast.LENGTH_SHORT);
			toast.show();
		}
	}

}
